package com.ruitu.health_2.ui.common;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.base.BaseModel;
import com.ruitu.arad.base.BasePresenter;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.health_2.R;
import com.ruitu.health_2.ui.activity.ArtManDetailActivity;
import com.ruitu.health_2.ui.activity.ArticleListByColumnActivity;
import com.ruitu.health_2.ui.activity.BookListByColumnActivity;
import com.ruitu.health_2.ui.activity.ReadPartieListByColumnActivity;
import com.ruitu.health_2.ui.activity.VideoListByColumnActivity;
import com.ruitu.health_2.ui.adapter.HorizonArtManListAdapter;
import com.ruitu.health_2.ui.fragment.ComActivityListFragment;
import com.ruitu.health_2.ui.fragment.ComArticleListFragment;
import com.ruitu.health_2.ui.fragment.ComBookListFragment;
import com.ruitu.health_2.ui.fragment.ComProListFragment;
import com.ruitu.health_2.ui.fragment.ComReadListFragment;
import com.ruitu.health_2.ui.fragment.ComVideoListFragment;
import com.ruitu.health_2.ui.mall.ProductListByColumnActivity;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.home.Advert;
import com.ruitu.router_module.bean.home.AdvertContent;
import com.ruitu.router_module.bean.home.Column;
import com.ruitu.router_module.bean.home.MallHomeData;
import com.ruitu.router_module.bean.product.ArtMan;
import com.ruitu.router_module.support.util.GlideImageLoader;
import com.ruitu.router_module.support.view.MeasuredNoScrollViewPager;
import com.ruitu.router_module.support.view.MyNestedScrollView;
import com.ruitu.router_module.support.view.OnTabSelectedListenerImpl;
import com.ruitu.router_module.util.GlideUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.config.Constants;
import me.dkzwm.widget.srl.indicator.IIndicator;

// 八个模块的基类
public abstract class BaseModel2Activity<P extends BasePresenter, M extends BaseModel> extends BaseActivity<P, M> {
    protected SmoothRefreshLayout refresh;// 外层刷新控件
    protected MyNestedScrollView scroll_view;// 滑动控件
    protected LinearLayout ll_scroll;// 所有滚动的内容

    protected Banner banner;
    protected ImageView iv_banner_holder;// banner的占位图
    protected RecyclerView rcv_10_menu;// 栏目
    protected RecyclerView rcv_art_man;// 艺人列表
    protected TextView tv_more_art_man;// 更多艺人

    protected XTabLayout tab, tab_2;// tab tab_2是默认隐藏的tab
    protected RelativeLayout rl_tab;// 包含tab_2和下边的分割线的布局
    protected RelativeLayout rl_container;// tab下面的容器
    protected MeasuredNoScrollViewPager vp_pro;// tab下面的vp

    /************************** 上面是view 下面是数据 **************************/
    protected MallHomeData mallHomeData;// 请求的商城首页数据

    protected List<Advert> advertiseList = new ArrayList<>();// banner广告轮播数据

    protected HorizonArtManListAdapter artManAdapter;// 艺人的adapter
    protected List<ArtMan> artManList = new ArrayList<>();// 横向艺人列表

    protected MenuAdapter menuAdapter;// 栏目的adapter
    protected List<Column> columnList = new ArrayList<>();// 栏目的数据

    protected String currPosId = "";// 记录当前选择的tab posId
    protected List<Column> tabColumnList = new ArrayList<>();// 栏目的数据
    protected VpAdapter vpAdapter;// tab下面的vp

    public static final String[] HOME_MODELS = {"- -", "- -", "- -", "- -", "- -"};// 新五大模块的布局 精选 读书会...
    protected int SCREEN_WIDTH = 0;// 屏幕的宽度
    protected int tabHei = 0;// tab的高度 50dp

    protected View header1, header2, header2_1, header3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        refresh = findViewById(R.id.refresh);
        scroll_view = findViewById(R.id.scroll_view);
        ll_scroll = findViewById(R.id.ll_scroll);
        tab_2 = findViewById(R.id.tab_2);
        rl_tab = findViewById(R.id.rl_tab);

        SCREEN_WIDTH = ScreenUtils.getScreenWidth();// 获取屏幕宽度
        tabHei = SizeUtils.dp2px(50);
        initRefreshView();

        LayoutInflater inflater = LayoutInflater.from(this);
        // Banner的布局
        header1 = inflater.inflate(R.layout.home_banner_layout, null, false);
        banner = header1.findViewById(R.id.banner);// Banner布局
        iv_banner_holder = header1.findViewById(R.id.iv_banner_holder);// Banner布局占位图
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) banner.getLayoutParams();
        params.width = SCREEN_WIDTH;
        params.height = params.width * 900 / 1800;// banner的比例是1800 * 900
        banner.setLayoutParams(params);
        iv_banner_holder.setLayoutParams(params);

        // 栏目的布局
        header2 = inflater.inflate(R.layout.home_menu_layout_grid, null, false);
        rcv_10_menu = header2.findViewById(R.id.rcv_10_menu);
        menuAdapter = new MenuAdapter(this);
        GridLayoutManager manager5 = new GridLayoutManager(this, 5);
        rcv_10_menu.setLayoutManager(manager5);
        rcv_10_menu.setAdapter(menuAdapter);
        for (int i = 0; i < 5; i++) {
            Column column = new Column();
            column.setName("加载中");
            columnList.add(column);
        }
        menuAdapter.setDataList(columnList);

        // 艺人的布局
        header2_1 = inflater.inflate(R.layout.model_home_art_man, null, false);
        rcv_art_man = header2_1.findViewById(R.id.rcv_art_man);
        tv_more_art_man = header2_1.findViewById(R.id.tv_more_art_man);
        LinearLayoutManager artManManager = new LinearLayoutManager(this);
        artManManager.setOrientation(RecyclerView.HORIZONTAL);
        rcv_art_man.setLayoutManager(artManManager);
        artManAdapter = new HorizonArtManListAdapter(this);
        rcv_art_man.setAdapter(artManAdapter);

        // tab五个模块
        header3 = inflater.inflate(R.layout.model_tab_layout, null, false);
        tab = header3.findViewById(R.id.tab);
        rl_container = header3.findViewById(R.id.rl_container);
        vp_pro = header3.findViewById(R.id.vp_pro);
        for (int i = 0; i < 5; i++) {
            tab.addTab(tab.newTab().setText(HOME_MODELS[i]), i);
            tab_2.addTab(tab_2.newTab().setText(HOME_MODELS[i]), i);
        }
        vp_pro.setOffscreenPageLimit(99);
        vp_pro.setScanScroll(false);
        vpAdapter = new VpAdapter(getSupportFragmentManager());

        scroll_view.post(new TopHeightRunnable());// 计算顶部高度

        ll_scroll.addView(header1);// Banner布局
        ll_scroll.addView(header2);// 10个功能菜单布局
        ll_scroll.addView(header2_1);// 横向艺人
        ll_scroll.addView(header3);// 八大模块

        setListeners();//设置一些监听
    }

    protected void setListeners() {
        setOnClickListener(tv_more_art_man);
        menuAdapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {
                if (!isDataEmpty(columnList)) {
                    String id = columnList.get(pos).getPosId();
                    String name = columnList.get(pos).getName();
                    onMenuItemClick(columnList.get(pos).getType(), id, name);
                } else {
                    ToastUtils.showShortSafe("请稍后重试");
                }
            }
        });
        artManAdapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                if (!isDataEmpty(artManList)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", artManList.get(position).getId());
                    bundle.putString("name", artManList.get(position).getName());
                    startActivity(ArtManDetailActivity.class, bundle);
                } else {
                    ToastUtils.showShortSafe("请稍后重试");
                }
            }
        });
        refresh.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                reqData();
                hideProgress();
                showProgress();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh.refreshComplete(false, 1000);
                    }
                }, 16000);
            }

            @Override
            public void onLoadingMore() {
                Logg.i("refresh加载更多...");
                "".charAt(0);
            }
        });
        refresh.addOnStatusChangedListener(new SmoothRefreshLayout.OnStatusChangedListener() {
            @Override
            public void onStatusChanged(byte old, byte now) {
//                Logg.i("onStatusChanged... old = " + old + ",now = " + now);
                if (now == SmoothRefreshLayout.SR_STATUS_INIT) {// 正常状态,显示搜索栏
                } else if (now == SmoothRefreshLayout.SR_STATUS_PREPARE) {// 正在下拉
                } else if (now == SmoothRefreshLayout.SR_STATUS_REFRESHING) {// 正在刷新
                } else if (now == SmoothRefreshLayout.SR_STATUS_COMPLETE) {// 刷新完成(还没有恢复)
                } else if (now == SmoothRefreshLayout.SR_STATUS_LOADING_MORE) {// 看意思是加载更多
                }
            }
        });
        refresh.addOnNestedScrollChangedListener(new SmoothRefreshLayout.OnNestedScrollChangedListener() {
            @Override
            public void onNestedScrollChanged() {
//                Logg.i("onNestedScrollChanged...");
            }
        });
        refresh.addOnUIPositionChangedListener(new SmoothRefreshLayout.OnUIPositionChangedListener() {
            @Override
            public void onChanged(byte status, IIndicator indicator) {
                // 这个回调和addOnStatusChangedListener回调的状态值是一样的
                // 区别:OnStatusChanged状态相同时不执行,只有状态改变时执行 onChanged:一直回调当前状态
            }
        });

        scroll_view.setScrollViewListener(new MyNestedScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(MyNestedScrollView scrollView, int x, int y, int oldx, int oldy) {
//                Logg.i("y = " + y + ",topHeight = " + topHeight + ",pageHeight = " + pageHeight);
                if (y > tabY) {// topHeight 滑动超过了顶部(banner + menu + 左右俩图)
                    rl_tab.setVisibility(View.VISIBLE);
                } else {
                    rl_tab.setVisibility(View.GONE);
                }
            }
        });
        tab.addOnTabSelectedListener(new OnTabSelectedListenerImpl() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                int tabIndex = tab.getPosition();
                currPosId = tabColumnList.get(tabIndex).getPosId();
                tab_2.getTabAt(tab.getPosition()).select();
            }
        });
        tab_2.addOnTabSelectedListener(new OnTabSelectedListenerImpl() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                BaseModel2Activity.this.tab.getTabAt(tab.getPosition()).select();
            }
        });
    }

    protected void initRefreshView() {
        refresh.setEnableAutoLoadMore(true);
        refresh.setDurationToCloseHeader(500);
        refresh.setDurationOfBackToKeepHeader(300);
        refresh.setEnableOverScroll(false);
//        refresh.setLoadingMinTime(1000);// 最少刷新一秒
        refresh.setMode(Constants.MODE_DEFAULT);// MODE_SCALE 仿小米下拉拉伸页面的效果
    }

    public void setDataToView() {
        initBanner(mallHomeData.getCarouselList());
        menuAdapter.setDataList(mallHomeData.getColumnList());// 设置栏目模块
        try {// 默认设置五个tab
            for (int i = 0; i < 5; i++) {
                tab.getTabAt(i).setText(tabColumnList.get(i).getName());
                tab_2.getTabAt(i).setText(tabColumnList.get(i).getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initBanner(final List<AdvertContent> bannerList) {
        List<String> urlList = new ArrayList<>();//图片地址集合
        List<String> introList = new ArrayList<>();//简介集合
        if (!isDataEmpty(bannerList)) {
            for (AdvertContent banner : bannerList) {
                urlList.add(banner.getImgUrl());
                introList.add("");//不显示banner简介
            }
        }
        if (isDataEmpty(urlList)) {
            banner.setVisibility(View.GONE);
            iv_banner_holder.setVisibility(View.VISIBLE);
            return;
        } else {
            banner.setVisibility(View.VISIBLE);
            iv_banner_holder.setVisibility(View.GONE);
        }
        try {
            banner.setImages(urlList);//设置图片集合
            banner.setImageLoader(new GlideImageLoader());//设置图片加载器
            banner.setDelayTime(6000);//设置轮播时间
            banner.setIndicatorGravity(BannerConfig.RIGHT);
            banner.setBannerAnimation(Transformer.Accordion);
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int pos) {
                    ToastUtils.showShortSafe("点击广告banner" + pos);
                }
            });
            banner.start();//banner设置方法全部调用完毕时最后调用
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // type 0-商品、1-文章、2-视频、3-活动、4-读书会、5-书籍、6-艺人 7-轮播图图片
    protected void onMenuItemClick(String type, String colId, String name) {
        Bundle bundle = new Bundle();
        bundle.putString("columnId", colId);
        bundle.putString("columnName", name);
        if (TextUtils.equals("0", type)) {
            startActivity(ProductListByColumnActivity.class, bundle);
        } else if (TextUtils.equals("1", type)) {
            startActivity(ArticleListByColumnActivity.class, bundle);
        } else if (TextUtils.equals("2", type)) {
            startActivity(VideoListByColumnActivity.class, bundle);
        } else if (TextUtils.equals("3", type)) {
            ToastUtils.showShortSafe("活动敬请期待");
        } else if (TextUtils.equals("4", type)) {
            startActivity(ReadPartieListByColumnActivity.class, bundle);
        } else if (TextUtils.equals("5", type)) {
            startActivity(BookListByColumnActivity.class, bundle);
        } else {
            ToastUtils.showShortSafe("未知数据类型");
        }
    }

    //banner下面的菜单项的adapter
    protected static class MenuAdapter extends ListBaseAdapter<Column> {
        public MenuAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.home_item_menu;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int pos) {
            TextView tv_menu_txt = holder.getView(R.id.tv_menu_txt);
            ImageView iv_menu_icon = holder.getView(R.id.iv_menu_icon);

            Column model = mDataList.get(pos);
            tv_menu_txt.setText(model.getName());
            GlideUtil.loadImg(model.getImgUrl(), iv_menu_icon);
        }
    }

    protected class VpAdapter extends FragmentPagerAdapter {

        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
//            int tabIndex = tab.getSelectedTabPosition();
            String posId = tabColumnList.get(position).getPosId();
            String type = tabColumnList.get(position).getType();
            // type 0-商品、1-文章、2-视频、3-活动、4-读书会、5-书籍、6-艺人 7-轮播图图片
            return getFragment(type, posId);
        }

        @Override
        public int getCount() {
            return 5;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return tabColumnList.get(position).getName();
        }
    }

    protected Fragment getFragment(String type, String posId) {
        if (TextUtils.equals("0", type)) {
            return ComProListFragment.newInstance(posId);
        }
        if (TextUtils.equals("1", type)) {
            return ComArticleListFragment.newInstance(posId);
        }
        if (TextUtils.equals("2", type)) {
            return ComVideoListFragment.newInstance(posId);
        }
        if (TextUtils.equals("3", type)) {
            return ComActivityListFragment.newInstance(posId);
        }
        if (TextUtils.equals("4", type)) {
            return ComReadListFragment.newInstance(posId);
        }
        if (TextUtils.equals("5", type)) {
            return ComBookListFragment.newInstance(posId);
        }

        return ComProListFragment.newInstance(currPosId);
    }

    protected int tabY = 0;// tab的y坐标

    // 计算首页顶部高度
    public class TopHeightRunnable implements Runnable {
        @Override
        public void run() {
            int[] position = new int[2];
            tab.getLocationInWindow(position);
            tabY = position[1];
        }
    }

    protected abstract void reqData();
}
